import { getMapGeocoder } from '@/api/common'
import { getCityId, hotCity } from '@/api/home'
import { getStorageCache, removeStorageCache, setStorageCache } from '@/common/cache'
import { isEmpty } from '@/common/helper/is'
// #ifdef APP-PLUS
import permision from '@/common/libs/permission'
// #endif

/**
 * 定位
 * description @address
 *
 */

//设置默认State
const getDefaultState = () => {
  return {
    // #ifdef MP
    showOpensetting: false,
    // #endif

    locationInfo: {
      longitude: '',
      latitude: '',
    },

    cityConfig: getStorageCache('cityConfig') || {
      cityId: '',
      cityName: '',
    },
  }
}
//初始化State
const state = getDefaultState()

const mutations = {
  // 设置实时定位信息
  SET_LOCATION_INFO: (state, location) => {
    state.locationInfo = location
  },

  // 设置当前选择定位城市
  SET_CITY_DATA: (state, { id = '', name = '', latitude = '', longitude = '' }) => {
    state.cityConfig.cityId = id
    state.cityConfig.cityName = name
    state.cityConfig.latitude = latitude
    state.cityConfig.longitude = longitude
    setStorageCache('cityConfig', state.cityConfig)
  },

  SET_OPENSETTING(state, status) {
    state.showOpensetting = status
  },

  RESET_STATE(state) {
    Object.assign(state, getDefaultState())
    removeStorageCache('cityConfig')
  },
}

const actions = {
  ResetState({ commit }) {
    commit('RESET_STATE')
  },

  // 获取gps定位经纬度
  GetLocation({ state, commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      let status = null
      // #ifdef APP-PLUS
      status = await permision.checkPermission('location')
      if (status !== 1) return
      // #endif

      // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
      status = await dispatch('getSetting')
      if (status === 2) {
        commit('SET_OPENSETTING', true)
      }
      // #endif

      const res = await dispatch('doGetLocation')
      // console.log('🚀 ~ newPromise ~ res:', res)
      if (!isEmpty(res) && res.latitude !== undefined) {
        await dispatch('doGetAddress')

        if (!state.cityConfig?.cityId) {
          await dispatch('getCityInfo')
        }
      } else {
        // 拒绝或未获取到定位经纬度时设置默认城市为‘苏州’ 不至于首页数据空白
        if (!state.cityConfig?.cityId) {
          commit('SET_LOCATION_INFO', { addressComponent: { city: '苏州市' } })
          await dispatch('getCityInfo')
        }
      }

      resolve()
    })
  },

  doGetLocation({ commit }) {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        // type: 'gcj02',
        success: (res) => {
          console.log('🚀 ~ doGetLocation ~ res:', res)
          const { longitude, latitude } = res
          commit('SET_LOCATION_INFO', { longitude, latitude })

          resolve(res)
        },
        fail: (err) => {
          console.log('🚀 ~ doGetLocation ~ err:', err)
          // uni.showModal({ content: `${JSON.stringify(err)}`, confirmText: '确定', showCancel: false })
          // #ifdef MP-BAIDU
          if (err.errCode === 202 || err.errCode === 10003) {
            // 202模拟器 10003真机 user deny
            commit('SET_OPENSETTING', true)
          }
          // #endif
          // #ifndef MP-BAIDU
          if (err.errMsg.indexOf('auth deny') >= 0) {
            uni.$uv.toast('访问位置被拒绝将会影响页面功能使用')
          } else {
            uni.$uv.toast(err.errMsg)
          }
          // #endif
          resolve(err)
        },
      })
    })
  },

  async doGetAddress({ state, commit }) {
    const {
      locationInfo: { latitude, longitude },
    } = state
    const params = {
      ...MAP.serveParams,
      location: MAP.Channel === 'AMAP' ? `${longitude},${latitude}` : `${latitude},${longitude}`,
    }
    const { status, result, regeocode } = await getMapGeocoder(params)
    // console.log('🚀 ~ doGetAddress ~ result:', result)
    let res = result || regeocode
    if (status === 0 && !isEmpty(res)) {
      // 统一返回关键对象属性key
      if (MAP.Channel === 'QMAP') res.addressComponent = res.address_component

      commit('SET_LOCATION_INFO', { latitude, longitude, ...res })
      // 没有默认值则 设置当前使用的定位配置信息cityConfig
    }
  },

  getSetting() {
    return new Promise((resolve, reject) => {
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] === undefined) {
            resolve(0)
            return
          }
          if (res.authSetting['scope.userLocation']) {
            resolve(1)
          } else {
            resolve(2)
          }
        },
      })
    })
  },
  openSetting({ dispatch }) {
    uni.openSetting({
      success: async (res) => {
        if (res.authSetting && res.authSetting['scope.userLocation']) {
          await dispatch('GetLocation')
          // 页面重载
          dispatch('loadPage')
        }
      },
      fail: (err) => {
        console.log('🚀 ~ openSetting ~ err:', err)
      },
      complete: () => {
        dispatch('cancelSetting')
      },
    })
  },
  cancelSetting({ commit }) {
    commit('SET_OPENSETTING', false)
  },

  // 获取cityData
  async getCityInfo({ state, commit, dispatch }) {
    const { addressComponent } = state.locationInfo

    const { city } = addressComponent

    const cityName = city && city.indexOf('市') > -1 ? city.replace('市', '') : city
    if (cityName) {
      const { errcode, data } = await getCityId({ city_name: cityName })
      if (errcode === 0) {
        if (isEmpty(data)) return uni.$uv.toast(`当前城市 ${cityName} 在未开放!`)
        commit('SET_CITY_DATA', data)
        // const { latitude, longitude } = data
        // if (latitude && longitude) commit('SET_LOCATION_INFO', { ...state.locationInfo, latitude, longitude })
        // 页面重载
        // dispatch('loadPage')
      }
    }
  },

  // 重载页面
  loadPage() {
    // 页面重载
    // 当前页面getCurrentPages
    const curPage = getCurrentPages().pop()
    if (curPage) {
      // 执行刷新
      curPage.$vm?.getData && curPage.$vm.getData()
    }
  },

  // 设置默认当前城市为‘苏州’
  SetCurDefaultCity({ state, commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      if (state?.cityConfig?.cityName.indexOf('苏州') < 0) {
        const { errcode, data } = await hotCity()
        if (errcode === 0) {
          const { all = [] } = data
          const cityList = all.length ? all.map((item) => item.list).flat() : []
          const city = cityList.find((item) => item.name.indexOf('苏州') > -1)
          if (city) {
            commit('SET_CITY_DATA', city)
            // dispatch('loadPage')
            resolve()
          }
        }
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
